<template>
  <a-card :bordered="false" title="i5xforyou-job命名空间下的作业列表">
    <template #extra>
      <a-space size="small">
        <a-input
          v-model:value="searchInput"
          :allow-clear="true"
          placeholder="请输入过滤条件"
          @change="searchInputChange"
        >
          <template #suffix>
            <SearchOutlined />
          </template>
        </a-input>
        <a-button type="primary" :disabled="refreshButtonDisable" :loading="refreshButtonDisable" @click="refresh">
          刷新
        </a-button>
      </a-space>
    </template>
    <a-spin size="large" :spinning="spinning">
      <a-table
        class="ant-table-striped"
        :data-source="dataSource"
        :columns="columns"
        :row-key="recode => recode.jobName"
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'statusDisplay'">
            <a-tag :color="jobStatusTagColor(record.status)">{{ jobStatusTagDisplay(record.status) }}</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <a-space size="small">
              <a-button
                v-show="record.status !== 'CRASHED'"
                type="primary"
                size="small"
                @click="$emit('showJobShardingTable', record.jobName)"
              >
                详情
              </a-button>
              <a-popconfirm
                :title="'确定要立即执行作业【' + record.jobName + '】吗？'"
                @confirm="triggerJob(record.jobName)"
              >
                <a-button v-show="record.status !== 'CRASHED' && editable" type="primary" danger size="small">
                  触发
                </a-button>
              </a-popconfirm>
              <a-popconfirm
                :title="'确定要生效作业【' + record.jobName + '】吗？'"
                @confirm="enableJob(record.jobName)"
              >
                <a-button
                  v-show="record.status === 'DISABLED' && editable"
                  type="primary"
                  size="small"
                  class="button-warning-enable"
                >
                  生效
                </a-button>
              </a-popconfirm>
              <a-popconfirm
                :title="'确定要失效作业【' + record.jobName + '】吗？'"
                @confirm="disableJob(record.jobName)"
              >
                <a-button
                  v-show="record.status === 'OK' && editable"
                  type="primary"
                  size="small"
                  class="button-warning-disable"
                >
                  失效
                </a-button>
              </a-popconfirm>
              <a-popconfirm
                :title="'确定要终止作业【' + record.jobName + '】吗？'"
                @confirm="shutdownJob(record.jobName)"
              >
                <a-button
                  v-show="record.status !== 'CRASHED' && editable"
                  type="primary"
                  size="small"
                  class="button-warning-shutdown"
                >
                  终止
                </a-button>
              </a-popconfirm>
              <a-popconfirm
                :title="'确定要删除作业【' + record.jobName + '】吗？'"
                @confirm="removeJob(record.jobName)"
              >
                <a-button
                  v-show="record.status === 'CRASHED' && editable"
                  type="primary"
                  size="small"
                  class="button-warning-remove"
                >
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-spin>
  </a-card>
</template>

<script setup lang="ts">
import * as jobApi from '@/api/job/job';
import { message } from 'ant-design-vue';
import { useStoreGlobalStore } from '@/store';
import { SearchOutlined } from '@ant-design/icons-vue';
//权限判断
const editable = useStoreGlobalStore().state.loginUser.role > 0;

defineEmits<{
  (e: 'showJobShardingTable', jobName: string): void;
}>();

let refreshButtonDisable = ref(false);

//刷新
function refresh() {
  refreshButtonDisable.value = true;
  message
    .loading('努力刷新中…')
    .then(() => {
      jobList();
    })
    .then(() => {
      message.success('刷新成功！');
      refreshButtonDisable.value = false;
    });
}

const columns = [
  {
    title: '作业名称',
    dataIndex: 'jobName',
  },
  {
    title: '作业分片总数',
    dataIndex: 'shardingTotalCount',
  },
  {
    title: 'Cron表达式',
    dataIndex: 'cron',
  },
  {
    title: '作业描述信息',
    dataIndex: 'description',
  },
  {
    title: '状态',
    key: 'statusDisplay',
  },
  {
    title: '操作',
    key: 'operation',
  },
];

let dataSource = ref([]);

onBeforeMount(() => {
  jobList();
});

//加载中
let spinning = ref(false);
//过滤
let searchInput = ref();
let orginJobList: any;

//获取作业列表
function jobList() {
  spinning.value = true;
  jobApi.jobList().then(jsonResult => {
    spinning.value = false;
    if (!jsonResult) {
      return;
    }
    dataSource.value = jsonResult.result;
    orginJobList = jsonResult.result;
  });
}

//过滤
function searchInputChange() {
  if (!searchInput.value) {
    //所有
    dataSource.value = orginJobList;
    return;
  }
  dataSource.value = orginJobList.filter((item: { jobName: string; description: string }) => {
    return (
      item.jobName.toLowerCase().includes(searchInput.value.toLowerCase()) ||
      item.description.toLowerCase().includes(searchInput.value.toLowerCase())
    );
  });
}

//状态
function jobStatusTagColor(jobStatus: string) {
  let jobStatusTag = 'success';
  if (jobStatus === 'OK') {
    jobStatusTag = 'success';
  } else if (jobStatus === 'CRASHED') {
    jobStatusTag = 'error';
  } else if (jobStatus === 'DISABLED') {
    jobStatusTag = 'warning';
  } else if (jobStatus === 'SHARDING_FLAG') {
    jobStatusTag = 'processing';
  }
  return jobStatusTag;
}

//状态
function jobStatusTagDisplay(jobStatus: string) {
  let jobStatusDisplay = '未知';
  if (jobStatus === 'OK') {
    jobStatusDisplay = '正常';
  } else if (jobStatus === 'CRASHED') {
    jobStatusDisplay = '已下线';
  } else if (jobStatus === 'DISABLED') {
    jobStatusDisplay = '已失效';
  } else if (jobStatus === 'SHARDING_FLAG') {
    jobStatusDisplay = '分片待调整';
  }
  return jobStatusDisplay;
}

//触发作业job
async function triggerJob(jobName: string) {
  await jobApi.triggerJob({ jobName: jobName }).then(jsonResult => {
    message.success(jsonResult?.message);
  });
  jobList();
}

//生效作业job
function enableJob(jobName: string) {
  jobApi.enableJob({ jobName: jobName }).then(jsonResult => {
    jobList();
    message.success(jsonResult?.message);
  });
}

//失效作业job
function disableJob(jobName: string) {
  jobApi.disableJob({ jobName: jobName }).then(jsonResult => {
    jobList();
    message.success(jsonResult?.message);
  });
}

//终止作业job
function shutdownJob(jobName: string) {
  jobApi.shutdownJob({ jobName: jobName }).then(jsonResult => {
    jobList();
    message.success(jsonResult?.message);
  });
}

//删除作业job
function removeJob(jobName: string) {
  jobApi.removeJob({ jobName: jobName }).then(jsonResult => {
    jobList();
    message.success(jsonResult?.message);
  });
}
</script>

<style lang="less" scoped>
.paddingTop {
  margin-top: 30px;
}

.button-warning-disable {
  background-color: #faad14;
  border-color: #faad14;
}

.button-warning-enable {
  background-color: #52c41a;
  border-color: #52c41a;
}

.button-warning-shutdown {
  background-color: #722ed1;
  border-color: #722ed1;
}

.button-warning-remove {
  background-color: #eb2f96;
  border-color: #eb2f96;
}

.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
</style>
